﻿using PracticeCentre.Common;
using PracticeCentre.Modeles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace PracticeCentre.Mvc.Filters
{
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
    public class LoginInterceptAttribute : ActionFilterAttribute
    {
        /// <summary>  
        /// OnActionExecuting是Action执行前的操作  
        /// </summary>  
        /// <param name="filterContext"></param>  
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //1.登录状态获取用户信息（自定义保存的用户）
            HttpCookie cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie == null)
            {
                //异步请求，返回JSON数据
                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        Status = -1,
                        Message = "登录已过期，请重新登录再进行操作!"
                    }
                };

            }
            else
            {
                //2.使用 FormsAuthentication 解密用户凭据
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(cookie.Value);
                //3.直接解析到用户模型里去
                SystemUser loginUser = JsonTool.JsonDeserialize<SystemUser>(authTicket.UserData);
                if (filterContext.HttpContext.Session["userInfo"] == null)
                {
                    //4.获取到的用户信息放入Session中
                    filterContext.HttpContext.Session["userInfo"] = loginUser;
                }
                //4. 将要使用的数据放到ViewData 里，方便页面使用
                filterContext.Controller.ViewData["UserName"] = loginUser.UserName;
                filterContext.Controller.ViewData["Portrait"] = loginUser.UserPass;
                filterContext.Controller.ViewData["UserID"] = loginUser.Id;
            }
            // 别忘了这一句。
            base.OnActionExecuting(filterContext);
        }

    }
}